package cn.sciento.farm.devicemanager.gateway.uplink.service.inverter.impl;

import cn.sciento.farm.devicemanager.common.constant.InverterError;
import cn.sciento.farm.devicemanager.common.constant.MqttConstant;
import cn.sciento.farm.devicemanager.dao.entity.DevInverter;
import cn.sciento.farm.devicemanager.dao.entity.DevInverterAlarm;
import cn.sciento.farm.devicemanager.gateway.model.inverter.InverterRealData;
import cn.sciento.farm.devicemanager.gateway.uplink.service.inverter.InverterDisposeService;
import cn.sciento.farm.devicemanager.service.InverterAlarmService;
import cn.sciento.farm.devicemanager.service.InverterService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Service;

/**
 * @author wumu
 */
@Order(1)
@Service(value = "InverterDataDisposeService")
public class InverterDataDisposeService implements InverterDisposeService {


    @Autowired
    private InverterAlarmService inverterAlarmService;

    @Autowired
    private InverterService deviceInverterService;

    @Override
    public void changeOnline(String eui, int online) {
        deviceInverterService.updateOnline(eui,online);
    }

    @Override
    public void changeParams(InverterRealData data) {
        DevInverter deviceInverter = deviceInverterService.getByEui(data.getEui());

        if(data.isStatusData()){
            // 更新变频器的参数或者状态
            if(deviceInverter == null){
                return;
            }
            deviceInverter.setMaxPressure(data.getHyperPress());
            deviceInverter.setMinPressure(data.getLowPress());
            deviceInverter.setStatus(data.getStatus());
            deviceInverter.setGivenPressure(data.getGivenPress());
            deviceInverter.setOnline(MqttConstant.DEVICE_ONLINE_CODE);
            deviceInverterService.updateById(deviceInverter);
        }else {
            if(data.getFault() != null && data.getFault() != 0){
                DevInverterAlarm deviceInverterAlarm = new DevInverterAlarm();
                deviceInverterAlarm.setInverterId(deviceInverter.getId());
                deviceInverterAlarm.setName(deviceInverter.getName());
                deviceInverterAlarm.setStartTime(System.currentTimeMillis());
                deviceInverterAlarm.setMessage(InverterError.match(data.getFault()).getMessage());
                deviceInverterAlarm.setStatusCode(data.getFault());
                inverterAlarmService.insert(deviceInverterAlarm);
            } else {
                deviceInverter.setPressure(data.getRealPress());
                deviceInverterService.updateById(deviceInverter);
            }
        }
    }

}
